package com.scy.btsmart.conf;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

public class ConfigParamManage {

	private static final String TAG = "ConfigParamManage";
	private static final String BTSMART_DEVICE_AGENT_PARAM = "BtSmartDeviceAgentParam";
	
	private static Map<String, ConfigParam> mConfMap = new HashMap<String, ConfigParam>();
	
	//加载配置参数
	public static void loadParam(Context context)
	{
		//加载配置参数
		try {
			loadDefaultConf(context);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.i(TAG, "loadDefaultConf(context);"+ e.getMessage());	
		}
		
		//加载设置参数
		SharedPreferences preferences = getSharedPreferences(context);
		
    	//遍历添加参数
        Iterator<ConfigParam> it = mConfMap.values().iterator();  
        while (it.hasNext()) { 
    		ConfigParam param = (ConfigParam)it.next();
    		if(param.getM_Type().equalsIgnoreCase(ConfigParam.VALUE_TYPE_STRING))
    		{
    			param.setM_Value(preferences.getString(param.getM_Key(), param.getM_Value()));
    		}
    		else if(param.getM_Type().equalsIgnoreCase(ConfigParam.VALUE_TYPE_INT))
    		{
    			param.setM_IntValue(preferences.getInt(param.getM_Key(), param.getM_IntValue()));
    		}
    		else
    		{
    			Log.i(TAG, "no support param type param");
    		}
        }
	}
	
	//保存配置参数
	public static int saveParam(Context context)
	{
		//取存储编辑器
    	Editor edit = getEditor(context);
 
    	//遍历添加参数
    	Iterator<ConfigParam> it = mConfMap.values().iterator(); 
    	while(it.hasNext()){
    		ConfigParam param = (ConfigParam)it.next();
    		if(param.getM_Type().equalsIgnoreCase(ConfigParam.VALUE_TYPE_STRING))
    		{
    			edit.putString(param.getM_Key(), param.getM_Value());
    		}
    		else if(param.getM_Type().equalsIgnoreCase(ConfigParam.VALUE_TYPE_INT))
    		{
    			edit.putInt(param.getM_Key(), Integer.parseInt(param.getM_Value()));
    		}
    		else
    		{
    			Log.i(TAG, "no support param type param");
    		}
    	}
    	
    	//更新参数
    	if(edit.commit())
    	{
    		Log.i(TAG, "commit param fail");
    		return -1;
    	}
    	
		return 0;
	}
	//取配置参数
	public static String getStringValue(String key, String defaultvalue)
	{
		ConfigParam param = mConfMap.get(key);
		if(param == null){
			return defaultvalue;
		}
		return param.getM_Value();
	}
	
	//取配置参数
	public static int getIntValue(String key, int defaultvalue)
	{
		ConfigParam param = mConfMap.get(key);
		if(param == null){
			return defaultvalue;
		}
		
		return param.getM_IntValue();
	}
	
	//取配置参数
	public static ConfigParam getConfigParam(String key)
	{
		ConfigParam param = mConfMap.get(key);
		return param;
	}
	
	//添加参数
	public static void addParam(ConfigParam param)
	{
		if(param.getM_Key() == null || param.getM_Key().isEmpty()){
			return;
		}
		
		ConfigParam tmpparam = mConfMap.get(param.getM_Key());
		if(tmpparam != null){
			mConfMap.remove(param.getM_Key());
		}
		
		mConfMap.put(param.getM_Key(), param);
	}
	
	//删除参数
	public static void delParam(String key)
	{
		ConfigParam tmpparam = mConfMap.get(key);
		if(tmpparam != null){
			mConfMap.remove(key);
		}
	}
	
	//修改参数
	public static void ModifyParam(ConfigParam param)
	{
		delParam(param.getM_Key());

		addParam(param);
	}
	
	//加载默认参数
	public static int loadDefaultConf(Context context) throws IOException
	{
    	//读取配置文件
    	InputStream in = context.getAssets().open("conf.xml");
    	FromXMLLoadParam(in);
    	in.close();
    	
    	return 0;
	}
	
	//从xml加载配置参数
	private static void FromXMLLoadParam(InputStream inStream)
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try 
        {
        	DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(inStream);
            Element root = (Element) dom.getDocumentElement();
            
            //查找所有Param节点
            NodeList items = root.getElementsByTagName("Param");
            for (int i = 0; i < items.getLength(); i++) 
            {
                //得到第一个Param节点
                Element personNode = (Element) items.item(i);
                
                String key = null;
                String value = null;
                String type = null;

                //获取Param节点下的所有子节点(标签之间的空白节点和key/value/type元素)
                NodeList childsNodes = ((Node) personNode).getChildNodes();
                for (int j = 0; j < childsNodes.getLength(); j++) 
                {
                	Node node = (Node) childsNodes.item(j); //判断是否为元素类型
                    if(node.getNodeType() == Node.ELEMENT_NODE)
                    {   
                    	Element childNode = (Element) node;
                    	//判断是否name元素
	                    if ("key".equals(childNode.getNodeName())) 
	                    {
	                    	//获取name元素下Text节点,然后从Text节点获取数据
	                    	key = ((Node) childNode).getFirstChild().getNodeValue();
	                    } 
	                    else if ("value".equals(childNode.getNodeName())) 
	                    {
	                    	value = ((Node) childNode).getFirstChild().getNodeValue();
	                    }
	                    else if ("type".equals(childNode.getNodeName())) 
	                    {
	                    	type = ((Node) childNode).getFirstChild().getNodeValue();
	                    }
                    }
                 }
                
                ConfigParamManage.addParam(new ConfigParam(key, value, type));
              }
        } 
        catch (Exception e) 
        {
        	Log.i(TAG, e.getMessage());
        }
    }
	
	//取存储编辑器
	private static Editor getEditor(Context context) 
	{
		SharedPreferences preferences = getSharedPreferences(context);
		return preferences.edit();
	}
    
	//取shared对象
	private static SharedPreferences getSharedPreferences(Context context) 
	{
		SharedPreferences preferences = context.getSharedPreferences(
				                        BTSMART_DEVICE_AGENT_PARAM, 
				                        Context.MODE_PRIVATE);
		return preferences;
	}
	
}
